package fp.poczadly.client.presenter;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

import fp.poczadly.client.LiveChatServiceAsync;
import fp.poczadly.client.event.LoginEvent;
import fp.poczadly.shared.User;
import fp.poczadly.shared.Utils;

public class LoginPresenter implements Presenter {

	public interface Display {
		HasClickHandlers loginButton();
		HasValue<String> usernameTextField();
		Widget asWidget();
	}
	
	private final LiveChatServiceAsync rpcService;
	private HandlerManager eventBus;
	private Display display;
	
	private User user;
	
	public LoginPresenter( LiveChatServiceAsync rpcService, HandlerManager eventBus, Display display ) {
		this.rpcService = rpcService;
		this.eventBus = eventBus;
		this.display = display;
		
		this.user = new User();
	}

	public void bind() {
		display.loginButton().addClickHandler( new ClickHandler() {
			
			@Override
			public void onClick( ClickEvent event ) {
				addUser();
			}
		} );
		
		rpcService.checkSession( Utils.USER, new AsyncCallback<User>() {

			@Override
			public void onFailure( Throwable caught ) {}

			@Override
			public void onSuccess( User result ) {
				eventBus.fireEvent( new LoginEvent( result ) );
			}
		} );
	}
	
	public void addUser() {
		user.setUsername( display.usernameTextField().getValue() );
		
		rpcService.addUser( user, new AsyncCallback<User>() {
			
			@Override
			public void onSuccess( User result ) {
				eventBus.fireEvent( new LoginEvent( result ) );
			}
			
			@Override
			public void onFailure( Throwable caught ) {
				Window.alert( user.getUsername() + Utils.USER_EXIST_IN_DB );
			}
		} );
	}
	
	@Override
	public void go( HasWidgets container ) {
		bind();
		
		container.clear();
		container.add( display.asWidget() );
	}

}
